package com.rxx.base.core;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.rxx.base.ViewRelated;
import com.rxx.base.theme.ThemeChange;
import com.rxx.theme.ZTheme;
import com.rxx.theme.ZThemeFileEntity;

import java.lang.reflect.Constructor;
import java.util.HashSet;
import java.util.Set;

/**
 * @author 冉超群
 * @date 2017/12/8-15:31
 * @desc
 */
public class ZThemeManager {

    protected ZTheme mZTheme = null;

    private final static Set<ThemeChange> mThemeChanges = new HashSet<>();

    private static volatile ZThemeManager mInstance;

    private ZThemeManager() {

    }

    public static ZThemeManager getInstance() {
        if (mInstance == null) {
            synchronized (ZThemeManager.class) {
                if (mInstance == null) {
                    mInstance = new ZThemeManager();
                }
            }
        }
        return mInstance;
    }

    public ZTheme getZTheme() {
        return mZTheme;
    }

    public void setZTheme(ZTheme zTheme) {
        this.mZTheme = zTheme;
    }

    /**
     * add  ThemeChange
     *
     * @param tag
     */
    public void addThemeChangeListener(ThemeChange tag) {
        mThemeChanges.add(tag);
    }

    /**
     * 移除 ThemeChange
     *
     * @param tag
     */
    public void removeThemeChangeListener(ThemeChange tag) {
        mThemeChanges.remove(tag);
    }

    /**
     * 切换主题
     *
     * @param themeFileEntity
     */
    public void changeTheme(ZThemeFileEntity themeFileEntity, Context context) {
        if (mZTheme != null && TextUtils.equals(mZTheme.getThemePath(), themeFileEntity.themePath)) {
            return;
        }
        mZTheme = ZTheme.createTheme(themeFileEntity, context);
        for (ThemeChange themeChange : mThemeChanges) {
            themeChange.onThemeChange(mZTheme);
        }
    }

    public ViewRelated getViewRelated() {
        ViewRelated phoneMateViewRelated = null;
        try {
            Class<?> tClass = getZTheme().getDexClassLoader().loadClass(ViewRelated.LOAD_CLASSNAME);
            Constructor<?> tConstructor = tClass.getConstructor();
            tConstructor.setAccessible(true);
            phoneMateViewRelated = (ViewRelated) tConstructor.newInstance();
        } catch (Exception e) {
            Log.e("ZApplication", "catch exception:" + e.toString());
            e.printStackTrace();
        }
        return phoneMateViewRelated;
    }

    public ZTheme createTheme(ZThemeFileEntity entity, Context context) {
        return ZTheme.createTheme(entity, context);
    }

}
